<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工考勤管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
    /* 基础样式 */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Segoe UI', system-ui, sans-serif;
    }

    html {
        font-size: 16px;
    }

    body {
        background: #f3f4f6;
    }

    /* 主容器 */
    .module-section {
        padding: 2rem 3rem;
        max-width: 1600px;
        margin: 0 auto;
    }

    /* 卡片样式增强 */
    .card {
        background: white;
        border-radius: 16px;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
        padding: 2rem;
        margin-bottom: 2rem;
        border: 1px solid #e5e7eb;
    }

    /* 标题系统 */
    .module-title {
        font-size: 1.75rem;
        color: #1f2937;
        margin-bottom: 2rem;
        display: flex;
        align-items: center;
        gap: 1rem;
        font-weight: 600;
    }

    .module-title i {
        font-size: 1.5em;
        color: #3b82f6;
    }

    /* 增强表单样式 */
    .multi-column-form {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 2rem;
        margin-top: 1.5rem;
    }

    .form-group label {
        display: block;
        margin-bottom: 0.75rem;
        color: #4b5563;
        font-weight: 500;
        font-size: 1rem;
    }

    input, select, textarea {
        width: 100%;
        padding: 1rem;
        border: 2px solid #e5e7eb;
        border-radius: 12px;
        font-size: 1rem;
        transition: all 0.2s;
        background: #f9fafb;
    }

    input:focus, select:focus, textarea:focus {
        border-color: #3b82f6;
        box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1);
        background: white;
    }

    /* 按钮样式优化 */
    .submit-btn {
        background: linear-gradient(135deg, #3b82f6, #2563eb);
        color: white;
        padding: 1rem 2rem;
        border-radius: 12px;
        border: none;
        cursor: pointer;
        font-size: 1rem;
        font-weight: 500;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 0.75rem;
    }

    .submit-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.3);
    }

    /* 表格优化 */
    .data-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0 0.75rem;
        margin-top: 1.5rem;
    }

    .data-table thead {
        background: #f8fafc;
    }

    .data-table th {
        padding: 1.25rem;
        font-size: 1rem;
        color: #64748b;
        font-weight: 600;
        text-align: left;
        border-bottom: 3px solid #e5e7eb;
    }

    .data-table td {
        padding: 1.25rem;
        background: white;
        border: 2px solid #f3f4f6;
        color: #374151;
        font-size: 1rem;
        transition: all 0.2s;
    }

    .data-table tr:hover td {
        transform: translateX(4px);
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
    }

    /* 状态标签增强 */
    .attendance-tag {
        display: inline-flex;
        padding: 0.5rem 1rem;
        border-radius: 8px;
        font-size: 0.9rem;
        font-weight: 500;
        align-items: center;
        gap: 0.5rem;
    }

    .tag-normal { background: #dcfce7; color: #166534; }
    .tag-late { background: #fef3c7; color: #b45309; }
    .tag-absent { background: #fee2e2; color: #b91c1c; }
    .tag-leave { background: #dcfce7; color: #166534; }

    /* 统计卡片 */
    .stat-card {
        background: linear-gradient(135deg, #f8fafc, #f1f5f9);
        padding: 1.5rem;
        border-radius: 16px;
        border-left: 4px solid #3b82f6;
        min-width: 240px;
    }

    .stat-value {
        font-size: 2.5rem;
        color: #1e3a8a;
        font-weight: 700;
        line-height: 1;
        margin-bottom: 0.5rem;
    }

    .stat-title {
        color: #64748b;
        font-size: 1rem;
        font-weight: 500;
    }

    /* 操作按钮组 */
    .action-group {
        display: flex;
        gap: 1.5rem;
        margin: 2rem 0;
    }

    /* 日历优化 */
    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 0.75rem;
        margin-top: 1.5rem;
    }

    .calendar-day {
        padding: 1.5rem;
        text-align: center;
        border-radius: 12px;
        background: white;
        border: 2px solid #f3f4f6;
        transition: all 0.2s;
    }

    .calendar-day:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);
    }

    /* 响应式优化 */
    @media (max-width: 1200px) {
        .module-section {
            padding: 1.5rem;
        }
        
        .multi-column-form {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 768px) {
        .multi-column-form {
            grid-template-columns: 1fr;
        }
        
        .stat-card {
            min-width: 100%;
        }
        
        .data-table td, 
        .data-table th {
            padding: 1rem;
            font-size: 0.95rem;
        }
    }

    /* 添加日历弹窗样式 */
    .calendar-modal {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: none;
        justify-content: center;
        align-items: center;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
    }
    .calendar-container {
        background: #fff;
        padding: 1rem;
        border-radius: 8px;
        max-width: 90%;
        max-height: 90%;
        overflow: auto;
    }
    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        grid-gap: 0.5rem;
        margin-bottom: 1rem;
    }
    .calendar-day.normal {
        background: #10B981;
        color: #fff;
    }
    .calendar-day.abnormal {
        background: #EF4444;
        color: #fff;
    }
    .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
    }
    .calendar-header button {
        background: transparent;
        border: none;
        font-size: 1.25rem;
        cursor: pointer;
    }
    .calendar-header span {
        font-size: 1.25rem;
        font-weight: 600;
    }
    </style>
</head>
<body>
    <div class="module-section">
        <!-- 顶部统计区 -->
        <div class="card">
            <div class="attendance-header">
                <div>
                    <h2 class="module-title">
                        <i class="fas fa-user-clock"></i>
                        员工考勤管理系统
                    </h2>
                    <p id="current-month-text" style="color: #6b7280; margin-top: 0.5rem;"></p>
                </div>
                <div class="stat-card">
                    <div class="stat-value" id="attendance-rate">0%</div>
                    <div class="stat-title">本月综合出勤率</div>
                </div>
            </div>
        </div>

        <!-- 考勤打卡区开始 -->
        <div class="card">
            <h3 class="module-title"><i class="fas fa-clock"></i> 考勤打卡</h3>
            <form id="attendance-form" class="multi-column-form">
                <div class="form-group">
                    <label>工号</label>
                    <input type="text" id="emp-code" placeholder="请输入工号">
                </div>
                <div class="form-group">
                    <label>姓名</label>
                    <input type="text" id="emp-name" placeholder="请输入姓名">
                </div>
                <div class="form-group" style="grid-column: 1 / -1; display: flex; gap: 1rem;">
                    <button type="button" id="punch-in-btn" class="submit-btn"><i class="fas fa-sign-in-alt"></i> 打卡</button>
                    <button type="button" id="punch-out-btn" class="submit-btn" style="background:linear-gradient(135deg,#ef4444,#dc2626)"><i class="fas fa-sign-out-alt"></i> 签退</button>
                    <button type="button" id="view-attendance-btn" class="submit-btn"><i class="fas fa-calendar-alt"></i> 查看考勤记录</button>
                </div>
            </form>
            <div id="attendance-message" style="margin-top:1rem;color:#10b981;"></div>
        </div>
        <!-- 考勤打卡区结束 -->

        <!-- 数据操作区 -->
        <div class="card">
            <div class="action-group">
                <button id="export-btn" class="submit-btn" style="background:linear-gradient(135deg,#10b981,#059669)">
                    <i class="fas fa-file-excel"></i>
                    导出考勤报表
                </button>
            </div>

            <!-- 数据表格 -->
            <table class="data-table">
                <thead>
                    <tr>
                        <th>工号</th>
                        <th>员工姓名</th>
                        <th>日期</th>
                        <th>签到时间</th>
                        <th>签退时间</th>
                        <th>工作时长</th>
                        <th>出勤状态</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 考勤记录通过脚本动态渲染 -->
                </tbody>
            </table>
            <!-- 分页控件，每页显示10条 -->
            <div class="pagination" style="margin-top: 1rem; text-align: center;">
                <button id="prev-record-page" class="submit-btn" style="margin-right:1rem;">上一页</button>
                <span id="record-page-info" style="margin:0 1rem;"></span>
                <button id="next-record-page" class="submit-btn" style="margin-left:1rem;">下一页</button>
            </div>
        </div>
    </div>

    <!-- 在</body>前插入日历弹窗HTML -->
    <div id="calendar-modal" class="calendar-modal">
        <div class="calendar-container">
            <div class="calendar-header">
                <button id="prev-month-btn">&lt;</button>
                <span id="calendar-month-year"></span>
                <button id="next-month-btn">&gt;</button>
            </div>
            <div class="calendar-grid" id="calendar-grid"></div>
            <button id="close-calendar-btn" class="submit-btn">关闭</button>
        </div>
    </div>
</body>
<script>
(function() {
    var attendanceRecords = [];
    var recordPage = 1;
    var pageSize = 10;
    var filterCode = '';
    var filterName = '';
    var currentYear = 0;
    var currentMonth = 0;

    function updatePageInfo() {
        var info = document.getElementById('record-page-info');
        if (info) {
            var totalPages = Math.ceil(attendanceRecords.length / pageSize) || 1;
            info.textContent = recordPage + '/' + totalPages;
        }
    }

    function renderCalendar(year, month) {
        var header = document.getElementById('calendar-month-year');
        header.textContent = year + '年' + (month + 1) + '月';
        var monthText = document.getElementById('current-month-text');
        if (monthText) { monthText.textContent = '当前月份：' + year + '年' + (month + 1) + '月'; }
        var grid = document.getElementById('calendar-grid');
        grid.innerHTML = '';
        // 获取今天日期，用于屏蔽未来日期的考勤显示
        var todayDate = new Date();
        todayDate.setHours(0,0,0,0);
        var normalStart = '09:00:00';
        var normalEnd = '18:00:00';
        var firstDay = new Date(year, month, 1).getDay();
        var daysInMonth = new Date(year, month + 1, 0).getDate();
        var presentCount = attendanceRecords.filter(function(r) {
            return r.code === filterCode && r.date.indexOf(year + '-' + ('0' + (month + 1)).slice(-2)) === 0 && r.in_time && r.out_time;
        }).length;
        var rateEl = document.getElementById('attendance-rate');
        if (rateEl) {
            var rate = daysInMonth > 0 ? (presentCount / daysInMonth * 100).toFixed(1) : '0';
            rateEl.textContent = rate + '%';
        }
        for (var i = 0; i < firstDay; i++) { grid.appendChild(document.createElement('div')); }
        for (var d = 1; d <= daysInMonth; d++) {
            // 对未来日期只显示日期，不显示考勤标签
            var cellDate = new Date(year, month, d);
            cellDate.setHours(0,0,0,0);
            if (cellDate > todayDate) {
                var dayCell = document.createElement('div');
                dayCell.className = 'calendar-day';
                dayCell.innerHTML = '<div class="day-number">' + d + '</div>';
                grid.appendChild(dayCell);
                continue;
            }
            var dateStr = year + '-' + ('0' + (month + 1)).slice(-2) + '-' + ('0' + d).slice(-2);
            var rec = attendanceRecords.find(function(r) { return r.code === filterCode && r.date === dateStr; });
            var cls = '';
            var label = '';
            if (rec) {
                if (rec.in_time && rec.out_time) {
                    var isLate = rec.in_time > normalStart;
                    var isEarly = rec.out_time < normalEnd;
                    if (isLate && isEarly) { cls = 'abnormal'; label = '迟到早退'; }
                    else if (isLate) { cls = 'abnormal'; label = '迟到'; }
                    else if (isEarly) { cls = 'abnormal'; label = '早退'; }
                    else { cls = 'normal'; }
                } else if (rec.in_time) {
                    cls = 'abnormal'; label = '迟到';
                } else if (rec.out_time) {
                    cls = 'abnormal'; label = '早退';
                } else {
                    cls = 'absent'; label = '缺勤';
                }
            } else {
                cls = 'absent'; label = '缺勤';
            }
            var dayCell = document.createElement('div');
            dayCell.className = 'calendar-day ' + cls;
            dayCell.innerHTML = '<div class="day-number">' + d + '</div>' + (label ? '<div class="day-label">' + label + '</div>' : '');
            grid.appendChild(dayCell);
        }
    }

    function renderRecords() {
        var tbody = document.querySelector('.data-table tbody');
        tbody.innerHTML = '';
        if (attendanceRecords.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" class="no-data">暂无记录</td></tr>';
            updatePageInfo();
            return;
        }
        var totalPages = Math.ceil(attendanceRecords.length / pageSize);
        recordPage = Math.max(1, Math.min(recordPage, totalPages));
        updatePageInfo();
        var start = (recordPage - 1) * pageSize;
        var pageRecords = attendanceRecords.slice(start, start + pageSize);
        pageRecords.forEach(function(rec) {
            var tr = document.createElement('tr');
            var status = '';
            var statusClass = '';
            if (rec.in_time && rec.out_time) {
                if (rec.in_time > '09:00:00' && rec.out_time < '18:00:00') { status = '迟到早退'; statusClass = 'tag-absent'; }
                else if (rec.in_time > '09:00:00') { status = '迟到'; statusClass = 'tag-late'; }
                else if (rec.out_time < '18:00:00') { status = '早退'; statusClass = 'tag-late'; }
                else { status = '正常'; statusClass = 'tag-normal'; }
            }
            var statusHtml = status ? '<span class="attendance-tag ' + statusClass + '"><i class="fas fa-check"></i>' + status + '</span>' : '';
            tr.innerHTML = '<td>' + rec.code + '</td>' +
                           '<td>' + rec.name + '</td>' +
                           '<td>' + rec.date + '</td>' +
                           '<td>' + (rec.in_time || '') + '</td>' +
                           '<td>' + (rec.out_time || '') + '</td>' +
                           '<td>' + (rec.duration || '') + '</td>' +
                           '<td>' + statusHtml + '</td>';
            tbody.appendChild(tr);
        });
    }

    function fetchRecords() {
        var url = '/api/attendance-records';
        if (filterCode) { url += '?code=' + encodeURIComponent(filterCode); }
        fetch(url)
            .then(res => res.json())
            .then(resp => {
                if (resp.success) {
                    attendanceRecords = resp.data;
                    renderRecords();
                }
            });
    }

    // 初始加载
    fetchRecords();

    document.getElementById('punch-in-btn').addEventListener('click', function() {
        var code = document.getElementById('emp-code').value.trim();
        var name = document.getElementById('emp-name').value.trim();
        if (!code || !name) { alert('请输入工号和姓名'); return; }
        var now = new Date();
        var date = now.toISOString().slice(0,10);
        var time = now.toTimeString().slice(0,8);
        fetch('/api/attendance-records/punch-in', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ code: code, name: name, date: date, inTime: time })
        })
        .then(res => res.json())
        .then(resp => {
            if (resp.success) {
                document.getElementById('attendance-message').textContent = '打卡成功';
                fetchRecords();
            } else {
                alert(resp.message || '打卡失败');
            }
        });
    });

    document.getElementById('punch-out-btn').addEventListener('click', function() {
        var code = document.getElementById('emp-code').value.trim();
        var name = document.getElementById('emp-name').value.trim();
        if (!code || !name) { alert('请输入工号和姓名'); return; }
        var now = new Date();
        var date = now.toISOString().slice(0,10);
        var time = now.toTimeString().slice(0,8);
        fetch('/api/attendance-records/punch-out', {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ code: code, date: date, outTime: time })
        })
        .then(res => res.json())
        .then(resp => {
            if (resp.success) {
                document.getElementById('attendance-message').textContent = '签退成功';
                fetchRecords();
            } else {
                alert(resp.message || '签退失败');
            }
        });
    });

    document.getElementById('view-attendance-btn').addEventListener('click', function() {
        filterCode = document.getElementById('emp-code').value.trim();
        filterName = document.getElementById('emp-name').value.trim();
        if (!filterCode || !filterName) { alert('请输入工号和姓名'); return; }
        var today = new Date(); currentYear = today.getFullYear(); currentMonth = today.getMonth();
        fetchRecords(); renderCalendar(currentYear, currentMonth);
        document.getElementById('calendar-modal').style.display = 'flex';
    });

    document.getElementById('prev-month-btn').addEventListener('click', function() {
        currentMonth--; if (currentMonth < 0) { currentYear--; currentMonth = 11; }
        fetchRecords(); renderCalendar(currentYear, currentMonth);
    });

    document.getElementById('next-month-btn').addEventListener('click', function() {
        currentMonth++; if (currentMonth > 11) { currentYear++; currentMonth = 0; }
        fetchRecords(); renderCalendar(currentYear, currentMonth);
    });

    document.getElementById('close-calendar-btn').addEventListener('click', function() {
        document.getElementById('calendar-modal').style.display = 'none';
    });

    document.getElementById('prev-record-page').addEventListener('click', function() {
        if (recordPage > 1) { recordPage--; renderRecords(); }
    });

    document.getElementById('next-record-page').addEventListener('click', function() {
        var totalPages = Math.ceil(attendanceRecords.length / pageSize);
        if (recordPage < totalPages) { recordPage++; renderRecords(); }
    });

    // 导出考勤报表功能
    document.getElementById('export-btn').addEventListener('click', function() {
        var headers = ['工号','员工姓名','日期','签到时间','签退时间','工作时长','出勤状态'];
        var rows = attendanceRecords.map(function(rec) {
            var status = '';
            if (rec.in_time && rec.out_time) {
                if (rec.in_time > '09:00:00' && rec.out_time < '18:00:00') status = '迟到早退';
                else if (rec.in_time > '09:00:00') status = '迟到';
                else if (rec.out_time < '18:00:00') status = '早退';
                else status = '正常';
            }
            return [rec.code, rec.name, rec.date, rec.in_time||'', rec.out_time||'', rec.duration||'', status];
        });
        var csvContent = '\uFEFF' + headers.join(',') + '\n' + rows.map(function(r) { return r.join(','); }).join('\n');
        var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        var link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        var filename = '考勤报表_' + new Date().toISOString().slice(0,10) + '.csv';
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
})();
</script>
</html>